﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ProdeFrontEnd.Clases;
using ProdeFrontEnd.ServiceReferenceUser;
using System.Security.Cryptography;
using System.Text;
 
namespace ProdeFrontEnd.Pags
{
    public partial class NewUser : System.Web.UI.Page
    {
        private ServiceUser serviceUser;
        private ServiceProde serviceProde;

        protected void Page_Load(object sender, EventArgs e)
        {
            serviceUser = ServiceUser.getInstanceServiceUser();
            serviceProde = ServiceProde.getInstanceServiceProde();
        }

        protected void Create_Click(object sender, EventArgs e)
        {
            try
            {
                User user = new User();
                user.code = Code.Text.Trim();
                user.name = Name.Text.Trim();
                user.mail = Mail.Text.Trim();
                user.password = Util.encryptPass(Password.Text, user.code);

                User user2 = serviceUser.userClient.createUser(user);
                Resultado.Text = "Usuario " + user2.name + " creado correctamente";
                deletInformationRegist();
            }
            catch(Exception ex)
            {
                Resultado.Text = ex.Message;
            } 
        }

        protected void login_Click(object sender, EventArgs e)
        {
            try
            {
                ProdeFrontEnd.ServiceReferenceProde.User user = new ProdeFrontEnd.ServiceReferenceProde.User();
                user.code = username.Text.Trim();
                user.password = Util.encryptPass(pass.Text, user.code);

                ProdeFrontEnd.ServiceReferenceProde.User userLogged = serviceProde.prodeClient.login(user);

                if (userLogged != null)
                {
                    Session.Timeout = 1;
                    Session["User"] = userLogged;                    
                    Response.Redirect("index.aspx");
                }
                Label1.Text = "Usuario o contraseña no validos";
            }
            catch (Exception ex)
            {
                Label1.Text = ex.Message;
            }
        }

        private void deletInformationRegist()
        {
            Code.Text = "";
            Password.Text = "";
            Name.Text = "";
            Mail.Text = "";
        }
    }
}